package com.yzi.utilitys
{
	import flash.utils.ByteArray;

	public class Base64Utility
	{
		private static const BASE64_CHAR:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		
		public function Base64Utility()
		{
			throw new Error("Static Class.");
		}
		
		static public function EncodeByByteArray($data:ByteArray): String
		{
			var result:String = "";
			var i:uint;
			var dataBuffer:Array;
			var outputBuffer:Array = new Array(4);
			
			$data.position = 0;
			
			while($data.bytesAvailable > 0)
			{
				dataBuffer = new Array();
				for(i = 0; i < 3 && $data.bytesAvailable > 0; ++i) dataBuffer[i] = $data.readUnsignedByte();
				
				outputBuffer[0] = (dataBuffer[0] & 0xfc) >> 2;
				outputBuffer[1] = ((dataBuffer[0] & 0x03) << 4) | (dataBuffer[1] >> 4);
				outputBuffer[2] = ((dataBuffer[1] & 0x0f) << 2) | (dataBuffer[2] >> 6);
				outputBuffer[3] = dataBuffer[2] & 0x3f;
				
				for(i = dataBuffer.length; i < 3; ++i) outputBuffer[i + 1] = 64;
				
				for(i = 0; i < outputBuffer.length; ++i) result += BASE64_CHAR.charAt(outputBuffer[i]);
			}
			
			return result;
		}
		
		static public function Encode($data:String): String
		{
			var bytes:ByteArray = new ByteArray();
			bytes.writeUTFBytes($data);
			
			return EncodeByByteArray(bytes);
		}
		
		static public function DecodeToByteArray($data:String): ByteArray
		{
			var result:ByteArray = new ByteArray();
			
			var dataBuffer:Array = new Array(4);
			var outputBuffer:Array = new Array(3);
			
			for(var i:uint = 0; i < $data.length; i += 4)
			{
				for(var j:uint = 0; j < 4 && (i + j) < $data.length; ++j) dataBuffer[j] = BASE64_CHAR.indexOf($data.charAt(i + j));
				
				outputBuffer[0] = (dataBuffer[0] << 2) + ((dataBuffer[1] & 0x30) >> 4);
				outputBuffer[1] = ((dataBuffer[1] & 0x0f) << 4) + ((dataBuffer[2] & 0x3c) >> 2);
				outputBuffer[2] = ((dataBuffer[2] & 0x03) << 6) + dataBuffer[3];
				
				for(var k:uint = 0; k < outputBuffer.length; ++k)
				{
					if(dataBuffer[k + 1] == 64) break;
					result.writeByte(outputBuffer[k]);				
				}
			}
			
			result.position = 0;
			
			return result;
		}
		
		static public function Decode($data:String): String
		{
			var bytes:ByteArray = DecodeToByteArray($data);
			
			return bytes.readUTFBytes(bytes.length);
		}
	}
}